<template>
  <section>
    <div class="header-wrap">

        <el-form :inline="true" :model="filters" label-width="100px" size="medium">
          <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
          <el-form-item label="账号：">
            <el-input v-model="filters.username" placeholder="请输入关键字搜索"></el-input>
          </el-form-item>
          <el-form-item label="启用状态：">
            <el-select v-model="filters.status" @change="getSearchStatus" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-on:click="searchUsers">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
          </el-col>
        </el-form>

    </div>
    <!-- 列表 -->
    <template>
      <el-table :data="getAllusers" style="width: 100%" :border="true">
        <el-table-column prop="username" label="账号" align="center">
        </el-table-column>
        <el-table-column prop="name" label="角色" align="center">
        </el-table-column>
        <el-table-column prop="fullname" label="姓名" align="center">
        </el-table-column>
        <el-table-column prop="phone" label="手机" align="center">
        </el-table-column>
        <el-table-column prop="status" label="启用状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 2">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" fixed="right" label="操作" min-width="140px" align="center">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.$index, scope.row)" size="mini" type="primary">编辑</el-button>
            <el-button type="danger" @click="handleDel(scope.$index, scope.row)" size="mini">删除</el-button>
            <el-button v-if="scope.row.status == 2" type="success" size="mini" @click="handleEnable(scope.$index, scope.row)">启用</el-button>
            <el-button v-if="scope.row.status == 0" type="warning" size="mini" @click="handleDisable(scope.$index, scope.row)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="float:right;margin-top:20px;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[10, 15, 20, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
        </el-pagination>
      </div>
    </template>
    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="100px" :rules="editFormRules" ref="editForm">
        <el-form-item label="角色" prop="name">
          <el-select @change="getNewCode" v-model="editValue" prop="name" value='name'>
            <el-option
              v-for="item in getRoleMenu"
              :key="item.value"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input v-model="editForm.username" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="fullname">
          <el-input v-model="editForm.fullname" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer2">
        <div style="margin-left:40px">
          <el-button type="primary" @click="resetPwd">重置密码</el-button>
        </div>
        <div>
          <el-button @click="editFormVisible = false">取消</el-button>
          <el-button type="primary" @click="editSubmit" :loading="editLoading">提交</el-button>
        </div>

      </div>
    </el-dialog>
    <!-- 新增 -->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" >
      <el-form :model="addForm" label-width="100px" :rules="rules2" ref="addForm">
        <el-form-item label="角色" prop="roleId">
          <el-select @change="getNewCode" v-model="addForm.roleId" placeholder="请选择">
            <el-option
              v-for="item in getRoleMenu"
              :key="item.value"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入账号" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="fullname">
          <el-input v-model="addForm.fullname" placeholder="请输入真实姓名" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addSubmit('addForm')" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script  type="text/ecmascript-6">
  import {fetch, post, removeUser} from '@/utils/http'
  export default {
    data() {
      let validatePhone = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('手机号不能为空'));
        } else if(!(/^1[34578]\d{9}$/.test(value))) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback();
        }
      };
      let validateRoleId = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择角色'));
        } else {
          callback();
        }
      };
      return {
        rules2: {
          roleId: [
            { validator: validateRoleId, trigger: 'change' }
          ],
          username: [
            {required: true, message: "请输入账号", trigger: 'blur' }
          ],
          fullname: [
            {required: true, message: "请输入真实姓名", trigger: 'blur' }
          ],
          phone: [
            { validator: validatePhone, trigger: 'blur' }
          ]
        },
        options: [{
          value: '',
          label: '全部'
        }, {
          value: '0',
          label: '启用'
        }, {
          value: '2',
          label: '禁用'
        }],
        newSearchStatus:"",
        newParsentCode:"",
        getRoleMenu:'',
        value1: '',
        name:'',
        getAllusers: [],
        totalCount: 0,
        pageIndex: 1,
        pageSize: 10,
        listLoading: false,
        sels: [],//列表选中列
        filters: {
          username: "",
          status: ""
        },
        editValue:'',//编辑页面的下拉框默认显示的值
        editFormVisible: false,//编辑界面是否显示
        editLoading: false,
        editFormRules: {
          username: [
//            { required: true, message: '请输入姓名', trigger: 'blur' }
          ]
        },
        //编辑界面数据
        editForm: {
          "id": "",
          "roleId": '',
          "username":"",
          "phone":"",
          "fullname":""
        },
        //新增界面是否显示
        addFormVisible: false,
        addLoading: false,
        //新增界面数据
        addForm: {
          'roleId':"",
          "username":"",
          "phone":"",
          "fullname":""
        }
      }
    },
    methods: {
      //重置密码
      resetPwd:function(index, row){
        this.$confirm('确认重置该用户密码吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          let para = {id: this.editForm.id};
          console.log(para)
          post('/api/manager/v1/user/resetPassword',para).then((response) => {
            console.log(response);
            this.listLoading = false;
            this.$message({
              message: '密码重置成功',
              type: 'success'
            });
          });
        }).catch(function(err) {
          console.log(err)
        });
      },
      //显示编辑界面
      handleEdit: function (index, row) {
        this.editFormVisible = true;
        this.getRoles();
        this.editForm = Object.assign({}, row);
        this.editValue = this.editForm.name;
      },
      //编辑
      editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              let para = {
                "id": this.editForm.id,
                "roleId": this.editForm.roleId,
                "username":this.editForm.username,
                "phone":this.editForm.phone,
                "fullname":this.editForm.fullname
              };
              if(this.newParsentCode){
                para.roleId = this.newParsentCode;
              }
              post('/api/manager/v1/user/updateUser',para).then((response) => {
                this.editLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
                this.editFormVisible = false;
                this.getUsers();
              });
            });
          }
        });
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.getUsers();
      },
      handleCurrentChange(val) {
        this.pageIndex = val;
        this.getUsers();
      },

      // 启用
      handleEnable: function (index, row) {
        this.$confirm('确认启用该用户吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          post('/api/manager/v1/user/startUser',{id: row.id}).then((response) => {
            this.listLoading = false;
            this.$message({
              message: '启用成功',
              type: 'success'
            });
            this.getUsers();
          });
        }).catch(function(err) {
          console.log(err)
        });
      },
      // 禁用
      handleDisable: function (index, row) {
        this.$confirm('确认禁用该用户吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          post('/api/manager/v1/user/banUser',{id: row.id}).then((response) => {
            console.log(response);
            this.listLoading = false;
            this.$message({
              message: '禁用成功',
              type: 'success'
            });
            this.getUsers();
          });
        }).catch(function(err) {
          console.log(err)
        });
      },
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          post('/api/manager/v1/user/deleteUser',{id: row.id}).then((response) => {
            this.listLoading = false;
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getUsers();
          });
        }).catch(function(err) {
          console.log(err)
        });
      },
      // 点击下来框，选中“全部”“启用”“禁用”进行搜索
      getSearchStatus(value) {
        // this.newSearchStatus = value;
        // console.log(this.newSearchStatus);
        // this.searchUsers();
      },
      //搜索
      searchUsers() {
        let para = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        };
        if(!this.filters.username.replace(/\s/g, "") == '') {
          para.username = this.filters.username.replace(/\s/g, "")
        }
        if(!this.filters.status == '') {
          para.status = this.filters.status
        }
        this.listLoading = true;
        // let _this = this;
        post('/api/manager/v1/user/accountQuery',para).then((response) => {
          this.getAllusers = response.data.data;
          this.totalCount = response.data.totalCount;
          console.log(response.data.totalCount);
          this.listLoading = false;
        }).catch(function(err) {
          console.log(err)
        });
      },
      //获取当前下拉框选中值的value代码值
      getNewCode(value) {
        this.newParsentCode = value;
        console.log(this.newParsentCode);
      },
      //显示新增界面
      handleAdd: function () {
        this.addFormVisible = true;
        this.getRoles();
        this.addForm = {
          'roleId': '',
          "username":"",
          "phone":"",
          "fullname":""
        };
      },
      //新增--选择角色
      getRoles() {
        this.listLoading = true;
        // let _this = this;
        post('/api/manager/v1/role/queryRole',{status: 0}).then((response) => {
          this.getRoleMenu = response.data.data;
          this.listLoading = false;
        }).catch(function(err) {
          console.log(err)
        });
      },
      //新增--提交
      addSubmit: function (addForm) {
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            let _this = this;
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.addLoading = true;
              let para = {
                fullname: this.addForm.fullname,
                phone: this.addForm.phone,
                username: this.addForm.username,
                roleId: this.newParsentCode
              };
              post('/api/manager/v1/user/addUser',para).then((response) => {
                this.addLoading = false;
                if(response.code == '42003'){
                  this.$message({
                    message: response.msg,
                    type: 'error'
                  });
                }else{
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  this.addFormVisible = false;
                  this.getUsers()
                }

              })
            });
          }
        });
      },

      //获取列表
      getUsers() {
        let para = {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        };
        this.listLoading = true;
        // let _this = this;
        post('/api/manager/v1/user/getUserList',para).then((response) => {
          this.getAllusers = response.data.data;
          this.totalCount = response.data.totalCount;
          this.listLoading = false;
        }).catch(function(err) {
          console.log(err)
        });
      },
    },
    mounted() {
      this.getUsers();
    }
  }
</script>

<style lang='scss' scoped>
  .dialog-footer2{
    display: flex;
    justify-content: space-between;
  }
  .header-wrap{
    height: 60px;
    padding-top: 20px;
    margin-bottom: 60px;
    background-color: #66BFBF;
    border-radius: 6px;
  }
  .center{
    height: 60px;
    display: flex;
    align-items: center;
  }
  .bg_green{
    background-color: greenyellow;
  }
  .bg_red{
    background-color: red;
  }
</style>
